/**
 * 初始化axios
 */
import Axios from 'axios'
import { Message } from 'element-ui'

class HttpRequest {
  constructor (baseUrl, header = {}) {
    this.baseUrl = baseUrl
    this.header = header
  }

  /**
   * 获取配置文件
   */
  getInsideConfig () {
    return {
      baseURL: this.baseUrl,
      header: this.header
    }
  }

  /**
   * 添加中间件
   * @param instance
   */
  interceptor (instance) {
    instance.interceptors.request.use(config => {
      return config
    }, error => Promise.reject(error))
    // 响应拦截器
    instance.interceptors.response.use(config => {
      // 弹出消息提示框
      if (config.data && config.data.msg !== '') {
        Message({
          message: config.data.msg,
          type: config.data.type
        })
      }
      return config.data
    }, error => {
      if (error.response.data && error.response.data.msg !== '') {
        Message({
          message: error.response.data.msg,
          type: error.response.data.type
        })
      }
    })
  }

  request (options) {
    Axios.defaults.withCredentials = true
    const instance = Axios.create()
    // 请求携带cookie
    options = Object.assign(this.getInsideConfig(), options)
    // 执行中间件
    this.interceptor(instance)
    return instance(options)
  }
}

export default HttpRequest
